package in.muton.edushare.registration.university;

import in.muton.edushare.EduSharePage;
import in.muton.edushare.EduShareSession;
import in.muton.edushare.url.URLLoader;
import in.muton.edushare.wicket.models.CayenneModel;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.HiddenField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.validation.validator.MaximumValidator;
import org.apache.wicket.validation.validator.MinimumValidator;
import org.apache.wicket.validation.validator.PatternValidator;
import org.apache.wicket.validation.validator.StringValidator;

import com.edushare.common.constants.ApplicationConstants;
import com.edushare.common.constants.URLConstants;
import com.edushare.common.dao.AcademicYearModelDAO;
import com.edushare.common.dao.UniversitiesDAO;
import com.edushare.common.util.StringUtil;
import com.edushare.common.vo.Universities;
import com.edushare.common.vo.UserRoles;
import com.edushare.common.vo.Users;

public class UnivInvite extends EduSharePage {
	
	private static Log log = LogFactory.getLog(UnivInvite.class);
	private String currentUniqueName;
	private String oldUniqueName;
	
	public UnivInvite(){
		super();
		//
		/** Assuming that one admin can hold only one university as Admin **/
		Users user = EduShareSession.get().getLoggedInUser();
		List<UserRoles> roles = user.getRoleList();
		UserRoles adminPersonna = null;
		for(UserRoles role: roles){
			if(role.getRoleType()== UserRoles.ADMIN_ROLE && role.getUniversity().getStatus() == Universities.UNIV_STATUS_INACTIVE){
				adminPersonna = role;
				break;
			}
		}		
		final IModel<Universities> universityModel = new CayenneModel<Universities>(adminPersonna.getUniversity());
		currentUniqueName = oldUniqueName = universityModel.getObject().getUniqueName();
		
		if(universityModel.getObject().getStatus() == Universities.UNIV_STATUS_ACTIVE){
			//this is one time thing return to Page not found
			setResponsePage(URLLoader.getPageClass(URLConstants.PAGE_NOT_FOUND_PATH));
			return;
		}
		
		final FeedbackPanel feedback = new FeedbackPanel("feedback");
		feedback.setOutputMarkupId(true);
		
		final HiddenField<String> semesterPattern = new HiddenField<String>("semList",new Model<String>(""));
		semesterPattern.setRequired(true);
		
		final Label univName = new Label("univFullName", universityModel.getObject().getUniversityName());
		final TextField<String> uniqueName = new TextField<String>("uniqueName",new PropertyModel<String>(this,"currentUniqueName"));
		uniqueName.setRequired(true);
		uniqueName.add(new PatternValidator("[A-Za-z0-9_\\-\\.]+"));
		uniqueName.add(StringValidator.minimumLength(ApplicationConstants.MIN_USERNAME_LENGTH));
		
//		final TextField<Integer> acadYr = new TextField<Integer>("acadYr", new PropertyModel<Integer>(university, "currentAcadYear"));
		
		Integer thisYr = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date()));
		List<Integer> YrArr = Arrays.asList(new Integer[]{thisYr-1, thisYr});
		final DropDownChoice<Integer> acadYr = new DropDownChoice<Integer>("acadYr", new Model<Integer>(YrArr.get(1)),YrArr);
		acadYr.setRequired(true);
//		acadYr.add(new PatternValidator("[1-2]\\d{3}"));
		acadYr.add(new MaximumValidator<Integer>(2100));
		acadYr.add(new MinimumValidator<Integer>(2009));
				
		final Label availability = new Label("availability", "");
		availability.setOutputMarkupId(true);
		uniqueName.add(new AjaxFormComponentUpdatingBehavior("onBlur"){
			
			private static final long serialVersionUID = -6662983891423518126L;
			
			@Override
			protected void onError(AjaxRequestTarget target, RuntimeException e) {
				
				if(!StringUtil.isValid(uniqueName.getInput())){
					availability.setDefaultModelObject("  INVALID");
					availability.add(new SimpleAttributeModifier("style", "color:red; font-weight:bold;"));
				}
				target.addComponent(availability);
				target.addComponent(feedback);
				super.onError(target, e);
			}
			
			@Override
			protected void onUpdate(AjaxRequestTarget target) {
				log.debug("uniqueName.getInput(): "+uniqueName.getInput());
				if(!StringUtil.isValid(uniqueName.getInput())){
					availability.setDefaultModelObject("  INVALID");
					availability.add(new SimpleAttributeModifier("style", "color:red; font-weight:bold;"));
				}else if(uniqueName.getInput().equals(oldUniqueName)){
					availability.setDefaultModelObject("");
				}else{
					if(new UniversitiesDAO(EduShareSession.get().getSessionORMInterface()).isUniqueNameAvailable(uniqueName.getInput())){
						availability.setDefaultModelObject("  AVAILABLE");
						availability.add(new SimpleAttributeModifier("style", "color:blue; font-weight:bold;"));
					}else{
						availability.setDefaultModelObject("  UNAVAILABLE");
						availability.add(new SimpleAttributeModifier("style", "color:red; font-weight:bold;"));
					}
				}
				target.addComponent(availability);
				target.addComponent(feedback);
			}
		});
		
		Form<Void> form = new Form<Void>("form"){
			@Override
			protected void onSubmit() {
				if(!StringUtil.isValid(currentUniqueName) || 
						! new UniversitiesDAO(EduShareSession.get().getSessionORMInterface()).isUniqueNameAvailable(uniqueName.getInput())){
					warn("Unique Short-name is invalid.");
				}else{
					
					String acadYearModelStr = semesterPattern.getConvertedInput();
					updateAcadYearModel(acadYearModelStr, universityModel.getObject());
					Users user = EduShareSession.get().getLoggedInUser();
					user.setStatus(Users.ACTIVE);
					user.setLandingPageId(Users.LANDING_PAGE_USER_HOME);
					universityModel.getObject().setUniqueName(uniqueName.getInput());
					universityModel.getObject().setCurrentAcadYear(acadYr.getConvertedInput());
					universityModel.getObject().setStatus(Universities.UNIV_STATUS_ACTIVE);
					setUserUnivRole(user, universityModel.getObject());
					getSessionORMInterface().commitAllChanges();
					setResponsePage(URLLoader.getPageClass(URLConstants.USER_PROFILE_PATH));
//					setResponsePage(URLLoader.getPageClass(URLConstants.UNIVERSITY_SETUP_PATH));
				}
			}

			private void setUserUnivRole(Users user, Universities university) {
				for(UserRoles ur: user.getRoleList()){
					if(ur.getUniversity()!=null && ur.getUniversity().getUniversityId()==university.getUniversityId()){
						ur.setCreationTimestamp(new Date());
						ur.setStatus(UserRoles.STATUS_ACTIVE);
						break;
					}
				}
			}
		};
		add(form);
		form.add(feedback);
		form.add(semesterPattern);
		form.add(univName);
		form.add(uniqueName);
		form.add(acadYr);
		form.add(availability);
		
		//
		
		
	}
	
	private void updateAcadYearModel(String acadYearModelStr, Universities university) {
		String[] seqSemNameArr = acadYearModelStr.split(";");
		for(String seqSemName: seqSemNameArr){
			String[] seqSemArr = seqSemName.split(":");
			String sequenceNo = seqSemArr[0];
			String semName = seqSemArr[1];
			String isCurrent = seqSemArr[2];
			new AcademicYearModelDAO(getEduShareSession().getSessionORMInterface(), university).
				create(Integer.parseInt(sequenceNo), semName,Integer.parseInt(isCurrent));
		}
	}

}
